package com.dqyt.khjc.service;

import com.alibaba.fastjson.JSON;
import com.dqyt.common.check.CheckTool;
import com.dqyt.common.constant.AuthorityID;
import com.dqyt.common.constant.Opt;
import com.dqyt.common.utils.RegularUtil;
import com.dqyt.common.utils.UserInfoUtil;
import com.dqyt.khjc.bean.*;
import com.dqyt.khjc.mapper.CustomerMapper;
import com.dqyt.khjc.mapper.CustomerUserMapper;
import com.dqyt.khjc.mapper.HistoryMapper;
import com.dqyt.khjc.swicth.SwitchConfig;
import com.dqyt.khjc.utils.IpUtil;
import com.dqyt.khjc.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 客户管理-待审核申请控制类
 */
@Service
public class CustomerUserService {

    @Autowired
    private CustomerUserMapper customerUserMapper;
    @Autowired
    private HistoryMapper historyMapper;
    @Autowired
    private CustomerMapper customerMapper;

    /**
     * 分页查询  客户管理-待审核申请
     *
     * @param request
     * @param page
     * @param size
     * @param userName
     * @param phone
     * @param customerId
     * @param dtype
     * @return
     */
    public ResultMsg getReviewApplyList(HttpServletRequest request, Integer page, Integer size, String userName, String phone, String customerId, String dtype) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.KHGL_DSHSQ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            if (page != null && size != null) {
                page = (page - 1) * size;
            }
            //分页查询数据
            List<CustomerUserBean> data = customerUserMapper.getReviewApplyList(page, size, userName, phone, Integer.parseInt(customerId), Integer.parseInt(dtype));
            //查询二级的
            List<CustomerBean> chall =  customerMapper.getCustomerListChaAll();
            for(CustomerUserBean customerUserBean :data){
                for(CustomerBean customerBean:chall){
                    if(customerUserBean.getChId() == customerBean.getCustomerId()){
                        customerUserBean.setChIdStr(customerBean.getEnterpriseName());
                    }
                }
            }
            //查询总条数
            Long total = customerUserMapper.getTotalNumber(userName, phone, Integer.parseInt(customerId), Integer.parseInt(dtype));
            RespPageBean bean = new RespPageBean();
            bean.setData(data);
            bean.setTotal(total);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(bean);
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 批量同意 待申请的请求
     *
     * @return
     */
    public ResultMsg batchHandle(HttpServletRequest request, int[] ids, String statue, String[] names,int[] cuidsArr) {
        ResultMsg ret = new ResultMsg();
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.KHGL_DSHSQ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            //参数判断
            if (null == ids || ids.length == 0 || null ==statue || "".equals(statue)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }

            // 处理数据
            customerUserMapper.batchHandle(ids, Integer.parseInt(statue));
            //批量修改企业的状态
            int []  cuids = duplicate(cuidsArr);

            customerMapper.cubatchHandle(cuids,1);
            ret.setCode(ResultMsg.SUCESS);


            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添加操作记录
                // 先取得用户ip
                String ip = IpUtil.getIpAddr(request);
                //被操作者名字
                String namesStr = JSON.toJSONString(names);
                //被操作者id
                String bopIdStr = JSON.toJSONString(ids);
                HistoryBean historyBean = new HistoryBean();
                historyBean.setMessage("[" + user.getUserName() + "] 同意了 " + namesStr + " 的 客户注册申请");
                historyBean.setType(Opt.KHGL_DSHSQ_TG);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(bopIdStr);
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                historyMapper.addHistory(historyBean);
            }
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    //方法1：通过List去重
    public static int[] duplicate(int [] arrStr) {
    List<Integer> list = new ArrayList<>();
    for (int i=0; i<arrStr.length; i++) {
        if(!list.contains(arrStr[i])) {
            list.add(arrStr[i]);
        }
    }
    int [] mc = new int[list.size()];
    for(int a=0;a<list.size();a++){
        mc[a]=list.get(a);
    }
    return mc;
}



    /**
     * 批量拒绝
     *
     * @param ids          id数组
     * @param refuseReason 拒绝理由
     * @return
     */
    public ResultMsg batchRefuse(HttpServletRequest request, int[] ids, String refuseReason, String[] names) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.KHGL_DSHSQ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            //参数判断
            if (null == ids || ids.length == 0 || refuseReason.length()>112) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }
            customerUserMapper.batchRefuse(ids, refuseReason);
            ret.setCode(ResultMsg.SUCESS);

            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添加操作记录
                // 先取得用户ip
                String ip = IpUtil.getIpAddr(request);
                //被操作者名字
                String namesStr = JSON.toJSONString(names);
                //被操作者id
                String bopIdStr = JSON.toJSONString(ids);
                HistoryBean historyBean = new HistoryBean();
                historyBean.setMessage("[" + user.getUserName() + "] 拒绝了 " + namesStr + " 的 客户注册申请");
                historyBean.setType(Opt.KHGL_DSHSQ_JJ);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(bopIdStr);
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }

        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * @param userName   客户人员名称
     * @param phone      客户人员手机
     * @param customerId 客户id
     * @param account    客户人员账号
     * @param password   客户人员密码
     * @param password2  确认密码
     * @param isopen   是否为默认联系人
     * @param enterpriseName  所属机构的名字
     * @return
     */
    @Transactional
    public ResultMsg addCustomerUser(HttpServletRequest request, String userName, String phone, int customerId,int chId,
                                     String account, String password, String password2,boolean isopen,String enterpriseName) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.KHGL_XZKHRYXX)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }


            //参数判断
            if (null== userName ||"".equals(userName) || userName.length() > 16 ||
                 null == phone || "".equals(phone) || !RegularUtil.isMobile(phone) || customerId == 0 ||
                 null ==account    || "".equals(account) || account.length() > 16 ||
                 null == password ||  "".equals(password) || !password.equals(password2)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }


            //根据手机查询客户人员信息表
            CustomerUserBean customerUserBean2 =   customerUserMapper.getCustomerUserByphone(phone);
            if(null !=customerUserBean2){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("该手机号码已经注册");
                return ret;
            }

            CustomerUserBean customerUserBean3 =  customerUserMapper.getCustomerUserByAccount(account);
            if(null !=customerUserBean3){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("该账号已经存在");
                return ret;
            }


            //数据库操作
            CustomerUserBean customerUserBean = new CustomerUserBean();
            customerUserBean.setChId(chId);
            customerUserBean.setCustomerId(customerId);
            customerUserBean.setPhone(phone);
            customerUserBean.setAccount(account);
            customerUserBean.setPassword(password);
            customerUserBean.setUserName(userName);
            customerUserBean.setAvatar("/head/def_tx.png");
            customerUserBean.setStatue(1);
            customerUserBean.setAddTime(TimeUtil.currentTimeMillis());
            customerUserBean.setAddUser(user.getUserName());
            customerUserBean.setUpdateTime(TimeUtil.currentTimeMillis());
            customerUserBean.setUpdateUser(user.getUserName());
            int res = customerUserMapper.addCustomerUser(customerUserBean);
            int res2 =0;
            //如果需要设置为默认联系人  则修改客户表的联系人字段
            if(isopen){
                res2= customerMapper.updateByContacts(customerId,userName,phone);
                //如果操作成功
                if(res2<0){
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("数据异常");
                    return ret;
                }
            }else{
                if(res<=0){
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("数据异常");
                    return ret;
                }
            }

            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("操作成功");

            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添加操作记录
                // 先取得用户ip
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                if(isopen){
                    historyBean.setMessage("[" + user.getUserName() + "] 新增了["+enterpriseName+"]的人员["+userName+"]，并且已经设为该公司的默认联系人");
                }else{
                    historyBean.setMessage("[" + user.getUserName() + "] 新增了["+enterpriseName+"]的人员["+userName+"]");
                }
                historyBean.setType(Opt.KHGL_XZKHRYXX_XZ);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(String.valueOf(customerUserBean.getCustomerUserId()));
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }


        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * @param userName   客户人员名称
     * @param phone      客户人员手机
     * @param customerId 客户id
     * @param account    客户人员账号
     * @return
     */
    @Transactional
    public ResultMsg updateCustomerUser(HttpServletRequest request, long customerUserId,String userName, String phone, int customerId,int chId,
                                     String account) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.KHGL_XZKHRYXX)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }


            //参数判断
            if (null== userName ||"".equals(userName) || userName.length() > 16 ||
                    null == phone || "".equals(phone) || !RegularUtil.isMobile(phone) || customerId == 0 ||
                    null ==account    || "".equals(account) || account.length() > 16) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }





            CustomerUserBean customerUserBean = customerUserMapper.getCustomerUserById(customerUserId);


            if(!customerUserBean.getAccount().equals(account)){
                //根据手机查询客户人员信息表
                CustomerUserBean customerUserBean2 =   customerUserMapper.getCustomerUserByphone(phone);
                if(null !=customerUserBean2){
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("该账号已经存在");
                    return ret;
                }
            }

            if(!customerUserBean.getPhone().equals(phone)){
                CustomerUserBean customerUserBean3 =  customerUserMapper.getCustomerUserByAccount(account);
                if(null !=customerUserBean3){
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("该手机号码已经注册");
                    return ret;
                }
            }

            //数据库操作
            customerUserBean.setCustomerId(customerId);
            customerUserBean.setChId(chId);
            customerUserBean.setPhone(phone);
            customerUserBean.setAccount(account);
            customerUserBean.setUserName(userName);
            customerUserBean.setUpdateTime(TimeUtil.currentTimeMillis());
            customerUserBean.setUpdateUser(user.getUserName());
            int res = customerUserMapper.updateCustomerUser(customerUserBean);

            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("操作成功");

            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添加操作记录
                // 先取得用户ip
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                historyBean.setMessage("[" + user.getUserName() + "] 修改了客户人员["+userName+"]的信息");
                historyBean.setType(Opt.KHGL_KHRYXXYL_XG);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(String.valueOf(customerUserBean.getCustomerUserId()));
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }

        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }




    /**
     * 分页查询  客户管理-客户人员信息一栏
     *
     * @param request
     * @param page
     * @param size
     * @param userName
     * @param phone
     * @param customerId
     * @return
     */
    public ResultMsg getKhryxxApplys(HttpServletRequest request, Integer page, Integer size, String userName, String phone, String customerId,int chId) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.KHGL_KHRYXXYL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            if (page != null && size != null) {
                page = (page - 1) * size;
            }
            //分页查询数据
            List<CustomerUserBean> data = customerUserMapper.getKhryxxApplys(page, size, userName, phone, Integer.parseInt(customerId),chId);

            //查询二级的
            List<CustomerBean> chall =  customerMapper.getCustomerListChaAll();

            for(CustomerUserBean customerUserBean :data){
                for(CustomerBean customerBean:chall){
                    if(customerUserBean.getChId() == customerBean.getCustomerId()){
                        customerUserBean.setChIdStr(customerBean.getEnterpriseName());
                    }
                }
            }


            //查询总条数
            Long total = customerUserMapper.getKhryxxTotalNumber(userName, phone, Integer.parseInt(customerId),chId);
            RespPageBean bean = new RespPageBean();
            bean.setData(data);
            bean.setTotal(total);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(bean);
        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 允许登陆 / 禁止登陆  客户人员信息一栏
     *
     * @param customerUserId
     * @param statue    1:允许登陆    2限制登录
     * @param userName 客户人员名称
     * @return
     */
    public ResultMsg loginKxryxxRes(HttpServletRequest request, long customerUserId,int statue,String userName) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {

            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否有客户信息一览的权限
//            if (!CheckTool.checkAuthority(user, AuthorityID.KHGL_KHRYXXYL)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }
            //参数检查
            if (customerUserId == 0) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }
            int res = customerUserMapper.loginKxryxxRes(customerUserId, statue);
            if (res <= 0) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("数据异常");
                return ret;
            }
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("操作成功");

            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添加操作记录
                // 先取得用户ip
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();

                if (statue == 2) {
                    historyBean.setMessage("[" + user.getUserName() + "] 禁止了： [" + userName + "] 登陆");
                    historyBean.setType(Opt.KHGL_KHRYXXYL_JZDL);
                } else {
                    historyBean.setMessage("[" + user.getUserName() + "] 允许了： [" + userName + "] 登陆");
                    historyBean.setType(Opt.KHGL_KHRYXXYL_YXDL);
                }
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId(String.valueOf(customerUserId));
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }



        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 查询所属机构下面的人员列表
     * @param request
     * @param customerId
     * @return
     */
    public ResultMsg getCuUsersByCuId(HttpServletRequest request,int customerId){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {

            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_Web(request);
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUser_Web(request);
            // 用户权限检查 是否可以管理待审核申请
//            if (!CheckTool.checkAuthority(user, AuthorityID.YPGL_SJYPDJ)) {
//                ret.setCode(ResultMsg.ERROR);
//                ret.setMsg("你没有对应的操作权限");
//                return ret;
//            }

            List<CustomerUserBean> data= customerUserMapper.getCuUsersByCuId(customerId);
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("查询成功");
            ret.setData(data);

        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }

}
